package com.cjg.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUCpc03 {
    public static void main(String[] args) {
        C c = new C();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                c.A();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                c.B();
            }

        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                c.C();
            }
        },"C").start();
    }
}
class C{
    private int unm=10;
    private Lock lock=new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    public void A(){
        lock.lock();
        try {
            //等待 业务 唤醒
            while (unm!=10){
                condition1.await();
            }
            unm=20;
            System.out.println(Thread.currentThread().getName()+":1");
            //唤醒二
            condition2.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void B(){
        lock.lock();
        try {
            //等待 业务 唤醒
            while (unm!=20){
                condition2.await();
            }
            unm=30;
            System.out.println(Thread.currentThread().getName()+":2");
            //唤醒二
            condition3.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void C(){
        lock.lock();
        try {
            //等待 业务 唤醒
            while (unm!=30){
                condition3.await();
            }
            unm=10;
            //唤醒二
            System.out.println(Thread.currentThread().getName()+":3");
            condition1.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
